#!/usr/bin/ruby
require "rubygems"
require "opengl"
require "glut"
require "m3g"
require "pp"


class MyGLUTWidget
  def initialize
    GLUT.Init
    GLUT.InitWindowSize  256, 256
    GLUT.InitDisplayMode GLUT::GLUT_DOUBLE | GLUT::GLUT_RGB | GLUT::GLUT_DEPTH
    GLUT.CreateWindow "Ruby-M3G"

    initialize_scene

    GLUT.ReshapeFunc  method(:reshape).to_proc()
    GLUT.DisplayFunc  method(:display).to_proc()
    GLUT.KeyboardFunc method(:keyboard).to_proc()
    GLUT.MouseFunc    method(:mouse).to_proc()
    GLUT.IdleFunc     method(:idle).to_proc()
  end

  def initialize_scene

    cam = M3G::Camera.new
    cam.look_at  0,0,5, 0,0,0, 0,1,0

    bg = M3G::Background.new
    bg.color = 0x7f1f1f7f


    img,   = M3G::Loader::load "moe-small.png"
    width  = img.width
    height = img.height

    cmp = M3G::CompositingMode.new
    cmp.depth_test_enable = true

    app1 = M3G::Appearance.new
    app1.compositing_mode = cmp

    spr1 = M3G::Sprite3D.new  true, img, app1
    spr1.translate  1,0,0
    spr1.crop = 0, 0, -width, height

    app2 = M3G::Appearance.new
    app2.compositing_mode = cmp

    spr2 = M3G::Sprite3D.new  false, img, app2
    spr2.translate  -1,0,0
    spr2.crop = 0, 0, width, height

    
    @wld = M3G::World.new
    @wld.child << cam
    @wld.child << spr1
    @wld.child << spr2
    @wld.active_camera = cam
    @wld.background    = bg

  end

  def reshape width, height
    g3d = M3G::Graphics3D::instance
    g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 1, 100
  end

  def display
    g3d = M3G::Graphics3D::instance
    g3d.render @wld
    GLUT.SwapBuffers()
  end
  
  def keyboard key, x, y
    if key == 113  # 'q'
      exit
    elsif key == 32 # ' '
    end
    GLUT.PostRedisplay
  end

  def mouse button, state, x, y
  end

  def idle
    GLUT.PostRedisplay
  end

  def start
    GLUT.MainLoop
  end

end


MyGLUTWidget.new.start

